﻿package com.railway.web.action;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.org.rapid_framework.page.Page;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.railway.common.base.BaseStruts2Action;
import com.railway.common.constants.SysConstant;
import com.railway.common.util.Json;
import com.railway.common.util.StaticMap;
import com.railway.common.util.StaticMethod;
import com.railway.files.model.Files;
import com.railway.files.service.IFilesManager;
import com.railway.files.vo.query.FilesQuery;
import com.railway.msg.constants.IConstant;
import com.railway.msg.service.IMsgReciveManager;
import com.railway.news.model.Category;
import com.railway.news.model.CategoryUserLink;
import com.railway.news.model.News;
import com.railway.news.service.ICategoryManager; 
import com.railway.news.service.INewsManager;
import com.railway.news.vo.query.NewsQuery;
import com.railway.notice.service.INoticeManager;
import com.railway.notice.vo.NoticeQuery;
import com.railway.system.model.SysUser;
import com.railway.system.service.ISysUserManager;
import com.railway.system.vo.query.SysUserQuery;

public class WebAction extends BaseStruts2Action implements Preparable,
		ModelDriven {
	private ICategoryManager categoryManager; 
	private IMsgReciveManager msgReciveManager;
	private INewsManager newsManager;
	private ISysUserManager sysUserManager;
	private IFilesManager filesManager;
	private INoticeManager noticeManager;
	protected static final String DEFAULT_SORT_COLUMNS = null;
	private static final String LIST_NEWS_JSP = "/news/list.jsp";
	private static final String LIST_VIDEOS_JSP = "/video/list.jsp";
	private static final String SHOW_NEWS_JSP = "/news/news.jsp";
	private static final String HB_TITLE = "/titles/hb_zhuanti.jsp";
	private static final String SAFE_TITLE = "/titles/anquan.jsp";
	private static final String JS_TITLE = "/titles/js_zhuanti.jsp";
	private static final String O_TITLE = "/titles/o_zhuanti.jsp";
	private static final String d_TITLE = "/titles/d_zhuanti.jsp";
	private static final String GRB = "/titles/grb.jsp";
	private static final String LGT = "/titles/lgt.jsp";
	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写 */
    public String newskeyword ;
	// 获取登录的用户名
	public String userName;
	// 获取输入的密码
	public String userPwd;

	private String param;

	/*
	 * public String getMenu() { Map map = StaticMap.SYS_MENU; return
	 * writeAjaxResponse(Json.toJson(map)); }
	 */

	public void prepare() throws Exception {
		// TODO Auto-generated method stub

	}

	public Object getModel() {
		// TODO Auto-generated method stub
		return null;
	}

	public String showNews() {
		return SHOW_NEWS_JSP;

	}

	public String showAddress() {
		return "/address/show.jsp";
	}

	public String showDuty() {
		return "/duty/show.jsp";
	}
	public String showPayment() {
		return "/payment/show.jsp";
	}
	public String showAjaxNews() {
		String current_news_id = this.getRequest().getParameter("newsid");

		try {
			News ns = (News) newsManager.getById(current_news_id);

			Map map = new HashMap();
			map.put("id",ns.getId());
			map.put("newstitle", ns == null ? "默认新闻标题" : ns.getTitle());
			map.put("newscreatetime", ns == null ? new Date() + "" : ns.getCreateTimeString());
			map.put("newsimgs",  ns.getDtitle());
			map.put("newscontent", ns == null ? "默认新闻内容"
					: (ns.getContentText() == null ? "" : ns.getContentText()));
			Category cat = categoryManager.getById(ns.getCatId());
			map.put("formUrl", ns == null ? "默认新闻标题" : ns.getFromUrl());
			map.put("categoryname", cat.getNames() == null ? "默认专题名" : cat
					.getNames()); 
			if(cat.getState()!=null&&cat.getState()==1&&isGrant(ns.getCatId())){
				map.put("id","");
				map.put("newstitle","");
				map.put("newscontent", ""); 
				
				map.put("categoryname","");
			}
			return writeAjaxResponse(Json.toJson(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return writeAjaxResponse("{newstitle:\"blanktitle\",newscreatetime:\"blankcreatetime\",newsimgs:\"2012040314221043973.png\",newscontent:\"blankcontent\",categoryname:\"blankcategory\"}");
	}

	public String getDuty() {

		FilesQuery query = newQuery(FilesQuery.class, DEFAULT_SORT_COLUMNS);
		query.setFileTypes(SysConstant.FILE_TYPE_DUTY);
		Page page = filesManager.findPage(query);
		List list = page.getResult();
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {

				Files f = (Files) list.get(i);
				Map map = new HashMap();
				map.put("addressid", f.getId());
				map.put("addressname", f.getNames());
				return writeAjaxResponse(Json.toJson(map));
			}
		}
		Map map = new HashMap();
		map.put("id", "");
		map.put("name", "");
		return writeAjaxResponse(Json.toJson(map));
	}
	public String showVedio() {
		String fileid = this.getRequest().getParameter("fileid"); 
		Files file = filesManager.getById(fileid); 
		if(file==null) {
			file=new Files();
		}
		this.getRequest().setAttribute("id", file.getId());
		this.getRequest().setAttribute("title", file.getNames());
		this.getRequest().setAttribute("url", file.getCtxpaths());
		this.getRequest().setAttribute("desc",file.getMemo());
		this.getRequest().setAttribute("createTime", file.getCreateTimeString());
		return "/video/showviedio.jsp";
	}
	public String getAddress() {

		FilesQuery query = newQuery(FilesQuery.class, DEFAULT_SORT_COLUMNS);
		query.setFileTypes(SysConstant.FILE_TYPE_ADDRESS);
		Page page = filesManager.findPage(query);
		List list = page.getResult();
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {

				Files f = (Files) list.get(i);
				Map map = new HashMap();
				map.put("addressid", f.getId());
				map.put("addressname", f.getNames());
				return writeAjaxResponse(Json.toJson(map));
			}
		}
		Map map = new HashMap();
		map.put("id", "");
		map.put("name", "");
		return writeAjaxResponse(Json.toJson(map));
	}
	public String getPayment() {

		FilesQuery query = newQuery(FilesQuery.class, DEFAULT_SORT_COLUMNS);
		query.setFileTypes(SysConstant.FILE_TYPE_PAYMENT);
		Page page = filesManager.findPage(query);
		List list = page.getResult();
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {

				Files f = (Files) list.get(i);
				Map map = new HashMap();
				map.put("addressid", f.getId());
				map.put("addressname", f.getNames());
				return writeAjaxResponse(Json.toJson(map));
			}
		}
		Map map = new HashMap();
		map.put("id", "");
		map.put("name", "");
		return writeAjaxResponse(Json.toJson(map));
	}

	// 获取摄影专题
	public String getImg() {

		String temp_types = this.getRequest().getParameter("fileTypes");
		if (temp_types != null) {
			FilesQuery query = newQuery(FilesQuery.class, DEFAULT_SORT_COLUMNS);
			query.setSortColumns("CREATE_TIME");
			query.setFileTypes(temp_types);
			Map map = new HashMap();
			try {
				Page page = filesManager.findPage(query);

				map.put("total", page.getTotalCount());
				map.put("rows", page.getResult());
			} catch (Exception e) {
				e.printStackTrace();
			}
			return writeAjaxResponse(Json.toJson(map));
		}
		return "";

	}

	// 获取新闻
	public String getNewsTop() {

		return writeAjaxResponse("");

	}

	// 获取新闻
	public String getTitle() {

		return writeAjaxResponse("");

	}

	public String displayDuby() {
		return "/duty/duty.html";
	}

	public String displayAddress() {
		return "/duty/address.html";
	}

	public String getNewsByTitle() {

		String title = this.getRequest().getParameter("title");
		java.util.LinkedHashMap map=new java.util.LinkedHashMap();
		List<News> list = newsManager.findByTitle(title);

		// 取得新闻按专题分类
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				News news = list.get(i);

				if (news.getCatId() != null && !news.equals("")) {
					String catId = news.getCatId();
					if (map.get(catId) == null) {
						Category cat = new Category();
						cat.setId(catId);
						cat.setNames(news.getCatNames());
						cat.setCaTypes(news.getCaTypes());
						if (news.getId() != null && !news.getId().equals("")) {
							List<News> newsList = cat.getNewsList();
							if (newsList == null) {
								newsList = new ArrayList();
							}
							newsList.add(news);
							cat.setNewsList(newsList);
						}

						map.put(catId, cat);

					} else {
						Category cat = (Category) map.get(catId);
						if (news.getId() != null && !news.getId().equals("")) {
							List<News> newsList = cat.getNewsList();
							if (newsList == null) {
								newsList = new ArrayList();
							}
							newsList.add(news);
							cat.setNewsList(newsList);
						}
						map.put(catId, cat);
					}
				}
			}
		}
		Set<Map.Entry<String, Category>> set = map.entrySet();
		List result = new ArrayList();
		for (Iterator<Map.Entry<String, Category>> it = set.iterator(); it
				.hasNext();) {
			Map.Entry<String, Category> entry = (Map.Entry<String, Category>) it
					.next();
			Category cat = entry.getValue();
			Category cattemp = categoryManager.getById(cat.getId());
			cattemp.setNewsList(cat.getNewsList());
			result.add(cattemp);
		}
		this.getRequest().setAttribute("catList", result);
		if (title != null && title.equals("safe")) {
			return SAFE_TITLE;
		}
		if (title != null && title.equals("js")) {
			return JS_TITLE;
		}
		if (title != null
				&& (title.equals("dj1") || title.equals("dj2") || title
						.equals("dj3"))) {
			return O_TITLE;
		}
		if (title != null
				&& (title.equals("zg1") || title.equals("zg2") || title
						.equals("zg3"))) {
			return d_TITLE;
		}
		if (title != null && title.equals("hb")) {
			return HB_TITLE;
		}
		if (title != null && title.equals("grb")) {
			return GRB;
		}
		if (title != null && title.equals("lgt")) {
			return LGT;
		}
		return "";
	}

	public String listVideos() {

		return LIST_VIDEOS_JSP;
	}

	public String listNews() {
		if(this.getRequest().getParameter("categoryid")!=null&& !"null".equals(this.getRequest().getParameter("categoryid")) && !"".equals(this.getRequest().getParameter("categoryid"))){
			Category cat = categoryManager.getById(this.getRequest().getParameter("categoryid"));
			this.getRequest().setAttribute("cateName", cat.getNames());
		}else{
			
		}
		return LIST_NEWS_JSP;
	}
 

	public String changePWD() {

		return "/changepwd.jsp";
	}

	public String savechagedpwd() {

		String pwd1 = this.getRequest().getParameter("pass_word");
		String pwd2 = this.getRequest().getParameter("pass_word1");
		if (pwd1 != null) {
			if (pwd1.equals(pwd2)) {
				String current_user_id = (String) this.getRequest()
						.getSession().getAttribute(SysConstant.USER_ID);
				SysUser u = sysUserManager.getById(current_user_id);
				u.setUserPwd(pwd1);
				sysUserManager.update(u);
				this.getRequest().getSession().setAttribute("password", pwd1);
			}
		}
		return null;
	}
	/**
	 * 
	 * @return
	 */
	public String listAjaxVideos() {
        
		Map map = new HashMap();
		
		FilesQuery query = newQuery(FilesQuery.class, DEFAULT_SORT_COLUMNS);
		query.setFileTypes(SysConstant.CATEGORY_TYPE_VIDEO_MANAGEMENT);
		Page page = null;
		query.setSortColumns("Create_time DESC");
		if(this.newskeyword!=null && !"null".equals(this.newskeyword) && !"".equals(this.newskeyword)){
			try { 
				newskeyword =URLDecoder.decode(this.newskeyword, "utf-8");
				query.setNames(newskeyword);
				page = filesManager.findPageByLike(query);
				
			} catch ( Exception e) {
				 e.printStackTrace();
			}
		}else{
			    page = filesManager.findPage(query);
		}

		
		map.put("total", page.getTotalCount());
		map.put("rows", page.getResult());
			
 
		return writeAjaxResponse(Json.toJson(map));

	}

	/**
	 * 
	 * @return
	 */
	public String listAjaxNews() {
        
		String newskeyword=null;
		if(this.newskeyword!=null){
			try { 
				newskeyword =URLDecoder.decode(this.newskeyword, "utf-8");
			} catch (UnsupportedEncodingException e) {
				 
			}
		}
		//System.out.println("newskeyword:" + newskeyword);
		Map map = new HashMap();
		String current_category = this.getRequest().getParameter("catId");
		if (current_category != null && !"null".equals(current_category) && !"".equals(current_category)) {
			Category cat = categoryManager.getById(current_category);
			NewsQuery query = newQuery(NewsQuery.class, DEFAULT_SORT_COLUMNS);
			query.setPageSize(500);
			query.setSortColumns("Create_time DESC");
			query.setCatId(current_category);
			Page page = newsManager.findPage(query);

			map.put("total", page.getTotalCount());
			map.put("rows", page.getResult());

			 
		}else if(newskeyword != null){
			
			NewsQuery query = newQuery(NewsQuery.class, DEFAULT_SORT_COLUMNS);
			query.setTitle(newskeyword);
			query.setPageSize(500);
			query.setSortColumns("Create_time DESC");
			Page page = newsManager.findPageLike(query);

			map.put("total", page.getTotalCount());
			map.put("rows", page.getResult());
			
		}
		return writeAjaxResponse(Json.toJson(map));

	}

	/**
	 * 获得当前登录用户接收到的消息数量
	 * 
	 * @return
	 */
	public String getMsgCountByUserId() {

		// 从Session中获得登录用户的id
		String current_user_id = (String) this.getRequest().getSession()
				.getAttribute("userId");

		Map map = new HashMap();

		if (current_user_id != null && !current_user_id.equals("")) {
			try {
				long temp = msgReciveManager
						.getMsgCountByUserID(current_user_id);

				map.put(IConstant.MSG_COUNT, temp);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return writeAjaxResponse(Json.toJson(map));
	}
/**
 * 
 * @return
 */
	public String webLogout() {
	
	
   	try {
			 this.getRequest().getSession().invalidate();//主动使session失效
				this.getRequest().getSession().setAttribute("userId", null);
				this.getRequest().getSession().setAttribute("username", null);
				this.getRequest().getSession().setAttribute("password", null);
	         this.getResponse().sendRedirect("/index.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
 		return "/index.jsp";
	}

	/**
	 * 得到当前公告
	 * 
	 * @return
	 */
	public String getLatestNotice() {

		NoticeQuery query = newQuery(NoticeQuery.class, DEFAULT_SORT_COLUMNS);
		query.setCurrenttime(new Date(System.currentTimeMillis()));

		query.setSortColumns("CREATE_TIME");

		Page page = noticeManager.findPage(query);
		Map map = new HashMap();
		map.put("total", page.getTotalCount());
		map.put("rows", page.getResult());

		return writeAjaxResponse(Json.toJson(map));
	}

	public String webLogin() {

		Boolean flag = false;
		String result = "";
		String userId = "";
		if (userName != null && userPwd != null && !userName.equals("")
				&& !userPwd.equals("")) {

			SysUserQuery queryTwo = newQuery(SysUserQuery.class,
					DEFAULT_SORT_COLUMNS);
			// 设置一个很大的 pagesize
			queryTwo.setUserName(userName);
			queryTwo.setUserPwd(userPwd);
			// queryTwo.setAreaId("web");
			Page pageTwo = sysUserManager.findPage(queryTwo);
			List<SysUser> userlist = pageTwo.getResult();
			for (SysUser u : userlist) {
				if ((u.getUserName().equals(userName))
						&& (u.getUserPwd().equals(userPwd))) {
					userId = u.getId();
					flag = true;
					this.getRequest().getSession().setAttribute("userId",
							userId);
					this.getRequest().getSession().setAttribute("username",
							u.getUserName());
					this.getRequest().getSession().setAttribute("password",
							u.getUserPwd());

				}
			}

		}

		if (!flag) {
			if (this.getRequest().getSession().getAttribute("username") == null
					|| getRequest().getSession().getAttribute("username")
							.equals("")) {
				result = "用户名、密码错误";
				this.getRequest().setAttribute("result", result);
				return "/index.jsp";
			}

		}
		try {
			this.getResponse().sendRedirect("/index.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/index.jsp";
	}

	public String getXW() throws Exception {

		String xwurls = StaticMethod.null2String(this.getRequest()
				.getParameter("xwurls"));
		int num = StaticMethod.null2int(this.getRequest()
				.getParameter("num"),5);
		StringBuffer result = new StringBuffer();
		URL postUrl = new URL(xwurls + "?rowCount=" + num);
		HttpURLConnection connection = (HttpURLConnection) postUrl
				.openConnection();

		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("GET");
		connection.setUseCaches(false);

		// connection.setInstanceFollowRedirects(true);
		connection
				.setRequestProperty("Content-Type", "text/html;charset=utf-8");

		try {
			connection.connect();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "UTF-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				result.append(line);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String temp = result
				.toString()
				.replace(
						"<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://tempuri.org/\">",
						"");
		temp = temp.replace("</string>", "");
		return writeAjaxResponse(temp);
	}
    public boolean isGrant(String catId){
    	boolean result=false;
    	
    	if(getRequest().getSession().getAttribute("username")==null||"".equals(getRequest().getSession().getAttribute("username"))){
    		
    		return true;
    	}else{
    		
    		String current_user_id=(String)getRequest().getSession().getAttribute("userId");
    		String current_user_Name=(String)getRequest().getSession().getAttribute("username");
    		if(current_user_Name.equals("admin")){
    			return false;
    		}
    		CategoryUserLink culinkquery = new CategoryUserLink();
    		culinkquery.setCategoryid(catId);
    		culinkquery.setUserid(current_user_id);
    		culinkquery.setState("V");
    		//		
    		List authlist = categoryManager.getPermitCategoriesByUser(culinkquery);
    		if(authlist!=null&&authlist.size()>0){
    			return false;
    		}else{
    			return true;
    		}
    	}
     
    }
	public String getParam() {
		return param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	public void setNewsManager(INewsManager manager) {
		this.newsManager = manager;
	}

	public void setSysUserManager(ISysUserManager sysUserManager) {
		this.sysUserManager = sysUserManager;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserPwd() {
		return userPwd;
	}

	public void setUserPwd(String userPwd) {
		this.userPwd = userPwd;
	}

	public void setFilesManager(IFilesManager filesManager) {
		this.filesManager = filesManager;
	}

	public void setMsgReciveManager(IMsgReciveManager msgReciveManager) {
		this.msgReciveManager = msgReciveManager;
	}

	public void setCategoryManager(ICategoryManager categoryManager) {
		this.categoryManager = categoryManager;
	}

	public void setNoticeManager(INoticeManager noticeManager) {
		this.noticeManager = noticeManager;
	}

	public String getNewskeyword() {
		return newskeyword;
	}

	public void setNewskeyword(String newskeyword) {
		this.newskeyword = newskeyword;
	}

}
